<?php

namespace App\Console\Commands\Schedule;

use App\Repository\UserRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;

class LibraryExpire extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'library:expire';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    protected $user;

    /**
     * LibraryExpire constructor.
     *
     * @param UserRepository $user
     */
    public function __construct(UserRepository $user)
    {
        $this->user = $user;

        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        /** @var Collection $libraryExpires */
        $libraryExpires = \App\Model\LibraryExpire::whereDate('expire', Carbon::today()->toDateString())->get();

        $libraryExpires->each(function($libraryExpire, $key){

            $user = $this->user->getUserByOpenId($libraryExpire->open_id);

            $reader = \LibraryService::getReader($user->number);

            if($reader){
                foreach ($reader as $book) {
                    if($book = \LibraryService::isTodayExpire($book)){
                        $this->notice($book, $user);
                    }
                }
            }

        });
    }

    private function notice($book, $user)
    {
        $data = [
            'first' => '您好，你借阅的图书今天将到期',
            'keyword1' => $book['detail']['name'],
            'keyword2' => $book['date'],
            'keyword3' => '1天',
            'remark' => '请及时归还，避免超期!',
        ];
        try{
            \WechatService::getApp()->notice->to($user->open_id)->uses(config('wechat.template.library_expire'))->andUrl(env('APP_URL').'library')->data($data)->send();
        }catch(\Exception $e){
        }
    }
}
